package com.wesley.framework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * ProxyFactory
 *
 * @author WangPanYong
 * @since 2021/11/17 11:46
 */
public class ProxyFactory<T> {

    /**
     * 动态代理
     */
    @SuppressWarnings("unchecked")
    public static <T> T getProxy(final Class<T> interfaceClass) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InnerInvocationHandler(interfaceClass));
    }

    static class InnerInvocationHandler implements InvocationHandler {

        private final Class target;

        public InnerInvocationHandler(Class target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if ("toString".equals(method.getName())) {
                System.out.println(" toString 方法跳过");
                return target.getName();
            }

//            String mock = System.getProperty("mock");
//            if (mock != null && mock.startsWith("return:")) {
//                return mock.replace("return:", "");
//            }

            Invocation invocation = new Invocation(target.getName(), method.getName(), method.getParameterTypes(), args);
            // 从注册中心获取服务地址
//            List<URL> urlList = RemoteMapRegister.get(target.getName());
            // 负载均衡
//            URL url = LoadBalance.random(urlList);
            URL url = new URL("127.0.0.1", 9002);
            Protocol protocol = ProtocolFactory.getProtocol();
            return protocol.send(url, invocation);
        }
    }

}
